package edu.upenn.seas.peerreview.smui

import scala.collection.mutable

/**
 * An implementation of the Board interface defined in BattleshipCommon file.
 * @see BattleshipCommon.scala
 */
private[smui] class BoardImpl(val width : Int, val height : Int) extends Board {
  assert(width > 0, "width must exceed 0")
  assert(height > 0, "height must exceed 0")
  
  protected val ocean : Map[Point, CellStatus] = Map()
  
  override def examine(coord : Point) : CellStatus = {
    if (!inRange(coord)) return CellStatus.Invalid
    ocean.get(coord) match {
      case None => CellStatus.Empty
      case Some(n) => n
    }
  }
  
  override def +(coord : Point, change : CellStatus) = {
    val newOcean = ocean + ((coord, change))
    new BoardImpl(width, height) { override val ocean = newOcean }
  }
  
  override def toString() = {
    val SPACING = 4
    val stringStack = for (j <- 0 to height-1) yield {
      val rows = for (i <- 0 to width-1) yield {
        examine(Point(i, j)) match {
          case CellStatus.Empty => "."
          case CellStatus.Hit => "X"
          case CellStatus.Miss => "~"
          case CellStatus.Ship(s) => "S"
          case CellStatus.Invalid => throw new RuntimeException()
        }
      }
      val titled = j.toString :: rows.toList
      titled.map(("%"+SPACING+"s").format(_)).toList.mkString("")
    }
    val divider = "-" * width * SPACING
    val headerLine = (" " :: (0 until width).toList).map(("%"+SPACING+"s").format(_)).mkString("") + " (X)"
    divider + "\n" + headerLine + "\n" + stringStack.mkString("\n") + "\n  (Y)\n" + divider
  }
}
  